<template>
  <div class="iframe">
    <div class="i-title">
      <h3>侦听模板引用</h3>
    </div>
    <div class="i-tip" ref="root" id="my">{{ tip2 }}</div>
    <div class="i-tip">
      {{ str }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

const root = ref(null);
let str = ref("");
let tip2 = ref("今天是一个好天气");
onMounted(() => {
  // DOM 元素将在初始渲染后分配给 ref
  console.log(root.value, "初始内容");
  str.value = root.value.innerHTML + " , " + root.value.id;
})

watch(tip2, (newValue, oldValue) => {
  str.value = newValue + " , " + root.value.id;
  if (root.value.id == 'red') {
    root.value.className = 'red';
  }
  else if (root.value.id == 'green') {
    root.value.className = 'green';
  }
})

setTimeout(() => {
  tip2.value = "明天可能会下雨";
  root.value.setAttribute("id", "red")
}, 2000)

setTimeout(() => {
  tip2.value = "后天又是大晴天";
  root.value.setAttribute("id", "green")
}, 4000)

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.red {
  color: red;
}

.green {
  color: green;
}
</style>
